package com.notes.dao.implement;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.notes.dao.ItemDao;
import com.notes.model.Item;
import com.notes.model.SelectItemData;
import com.notes.model.User;
@Component
public class ItemDaoImplement implements ItemDao{
	@Resource
	private SessionFactory sessionFactory;
	DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm");
	Date date = new Date();
	
	@Override
	public void addItem(String text, Long userId,Date remindTime) {
		Session session = sessionFactory.getCurrentSession();	
		Item item = new Item();
		
		item.setDate(dateFormat.format(date));
		item.setText(text);
		item.setDeleteIndicator("N");
		item.setCompleteIndicator("N");
		item.setRemindTime(remindTime);
		Query q = session.createQuery("from User u where userId = :userId");
		q.setLong("userId", userId);
		List result = q.list();
		item.setUser((User) result.get(0));
		session.save(item);
		
		((User)result.get(0)).getItemSet().add(item);
		
	}
	
	
	@Override
	public void itemDelete(Long userId, List<SelectItemData> selectedList) {
		Session session = sessionFactory.getCurrentSession();
		for(SelectItemData sData:selectedList){
			Query itemQ = session.createQuery("UPDATE Item set deleteIndicator=:status"+" WHERE itemId=:itemId");
			itemQ.setLong("itemId", sData.getItemId());
			itemQ.setString("status", "Y");
			itemQ.executeUpdate();
			
		}
	}
		
		
		@Override
		public void itemDone(Long userId, List<SelectItemData> selectedItemSet) {
			Session session = sessionFactory.getCurrentSession();
			
			for(SelectItemData sData:selectedItemSet){
				Query queryItem = session.createQuery("UPDATE Item set completeIndicator = :status "  + 
	             "WHERE itemId = :itemId");
				queryItem.setString("status", "Y");
				queryItem.setLong("itemId", sData.getItemId());
				queryItem.executeUpdate();
			}
		}


		@Override
		public List<Item> itemDoneHistory(Long userId) {
			Session session = sessionFactory.getCurrentSession();
			Query queryDoneItem = session.createQuery("from Item where userId = :userId and completeIndicator= :status");
			queryDoneItem.setLong("userId", userId);
			queryDoneItem.setString("status", "Y");
			List<Item> result = queryDoneItem.list();
			return result;
		}


		@Override
		public List<Item> getItemListByUserId(Long userId) {
			Session session = sessionFactory.getCurrentSession();
			Query queryAllItem = session.createQuery("from Item where userId = :userId");
			queryAllItem.setLong("userId", userId);
			List<Item> result = queryAllItem.list();
			return result;
		}
}
